package com.roc.web.action.agent;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.MerinfoStop;
import com.roc.pojo.Operators;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.merinfo.MerchantBelongAction;
import com.roc.web.action.merinfo.MerchantBelongSearchCondition;

@Component
@Namespace("/agentAff") 
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AgentAffiliationAction  extends PaginationBaseAction{
	private static Logger logger = Logger.getLogger(AgentAffiliationAction.class);

	private AgentAffiliationSearchCondition searchCondition;
	
	@Autowired
	private IPageService pagenitionService;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	/**
	 * 代理商归属详情主页
	 * @Title: init
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/agent/agentAffiliation.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String init(){
		Operators op = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(!op.getRoleType().equals(Role.AGENT.getCode()) && !op.getRoleType().equals(Role.SYSTEM.getCode())
					&&!op.getRoleType().equals(Role.CLEAR_LEAD.getCode())&&!op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					 && !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())
					 && !op.getRoleType().equals(Role.O_MANAGER.getCode()) ){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			
		} catch (Exception e) {
			logger.error("查询代理商归属详情页面初始化异常", e);
			addActionError("查询代理商归属详情页面初始化异常");
		}
		return SUCCESS;
	}
	
	/**
	 * 查询代理商归属详情
	 * @Title: queryAgentAffiliation
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value = "queryAgentAffiliation", results = { @Result(name = "success", location = "/pages/agent/agentAffiliation.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryAgentAffiliation(){
		
		 Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(searchCondition == null){
			searchCondition = (AgentAffiliationSearchCondition) getSearchConditionFromSession();
			if(searchCondition == null){
				searchCondition = new AgentAffiliationSearchCondition();
			}
		}
		if(searchCondition.getMinDate()==null||searchCondition.getMinDate().equals("")||searchCondition.getMaxDate()==null||searchCondition.getMaxDate().equals("")){
			 logger.info("代理商归属详情查询时间为空");
			   return SUCCESS;
		   }
		
		try {

			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");

        	searchCondition.setOrgCode(orgCode);//当前查询人员所属机构
            searchCondition.setOneOrgCode( op.getOneagentid() );// 一级机构编号
			
			
			searchCondition.setOpId(opRealId);//id
			searchCondition.setCurrrentRoleType(superRole);//角色
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
				
				List<Operators> lists=new ArrayList<Operators>();
				if(searchRsList!=null&&searchRsList.size()>0)
				{
					Iterator<?> iterator=searchRsList.iterator();
					while(iterator.hasNext())
					{
						Object[] obj=(Object[]) iterator.next();
						Operators oper=new Operators();
						
						oper.setAccountNo(Constance.Null2EmptyTrim(obj[0]));     //代理商账号
						String phone = Constance.Null2EmptyTrim(obj[1]);         //手机号码
						if(null != op.getAgentType() && !op.getAgentType().equals("1")){
							oper.setMobile(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号 
                        }else{
                        	oper.setMobile(phone);//手机号
                        }
				//		oper.setMobile(Constance.Null2EmptyTrim(obj[1]));        //手机号
						oper.setOneagentName(Constance.Null2EmptyTrim(obj[2]));  //一级代理商
						oper.setRealName(Constance.Null2EmptyTrim(obj[3]));      //名称
						
						String cardNo = Constance.Null2EmptyTrim(obj[4]);
						if(null != op.getAgentType() && !op.getAgentType().equals("1")){
							oper.setCardNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号  
                        }else{
                        	oper.setCardNo(cardNo);// 证件号
                        }
						//oper.setCardNo(Constance.Null2EmptyTrim(obj[4]));        //证件号码
						oper.setCompanyName(Constance.Null2EmptyTrim(obj[5]));   //所属大区
						
				
					
						lists.add(oper);
					}
					searchRsList.clear();
					searchRsList.addAll(lists);
				}
			}
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
	   return SUCCESS;
    }
	
	
	


		public static String Null2EmptyTrim(Object obj) {
			if(obj==null){
				return "";
			}
			String str=String.valueOf(obj);
			if (str == null||"".equals(str)) {
				return "";
			} 
			return str.trim();
		}
	

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MERCHANT_AGENT_AFFI, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (AgentAffiliationSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERCHANT_AGENT_AFFI);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}


	public AgentAffiliationSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(AgentAffiliationSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


}

